<template>
  <!-- 弹框 dom -->
  <div id="popup" class="ol-popup" ref="mapContent" v-html="mapText"></div>
  <el-dialog v-model="isShowTraceCountsManage"
             :direction="direction"
             width="25%"
             :modal="false"
             style="position: absolute;left: 205px"
             draggable>
    <template #header>
      <h2>单车流量</h2>
    </template>
    <template #default>
      <div class="traceDate">
        <el-radio v-model="traceCountsDateRadio" label='gj20201221' size="large"
        >2020-12-21</el-radio>
      </div>
      <div class="traceClass" style="margin-top: 10px;margin-left: 40px" v-show="isShowTraceClass">
        <h4 style="margin-left: -200px">单车流量等级划分：</h4>
        <ul class="traceClassUl" style="margin: 10px">
          <li class="traceClassLi" >
             <div style="background-color: #2b93ce;width: 30px;height: 10px;margin:10px 0px 10px 0px"></div>
             <span class="PolygonStyle_fillType_05" style="margin: auto">空闲路段(=0)</span>
          </li>
          <li class="traceClassLi" >
            <div style="background-color: #00b514;width: 30px;height: 10px;margin:10px 0px 10px 0px"></div>
            <span class="PolygonStyle_fillType_05" style="margin: auto">较小流量路段(0~100)</span>
          </li>
          <li class="traceClassLi" >
            <div style="background-color: #c1ff24;width: 30px;height: 10px;margin: 10px 0px 10px 0px"></div>
            <span class="PolygonStyle_fillType_05" style="margin: auto">小流量路段(100~200)</span>
          </li>
          <li class="traceClassLi" >
            <div style="background-color: #eae830;width: 30px;height: 10px;margin: 10px 0px 10px 0px"></div>
            <span class="PolygonStyle_fillType_05" style="margin: auto">中等流量路段(200~300)</span>
          </li>
          <li class="traceClassLi" >
            <div style="background-color: #e0ad07;width: 30px;height: 10px;margin: 10px 0px 10px 0px"></div>
            <span class="PolygonStyle_fillType_05" style="margin: auto">较高流量路段(300~400)</span>
          </li>
          <li class="traceClassLi" >
            <div style="background-color: #bb8104;width: 30px;height: 10px;margin: 10px 0px 10px 0px"></div>
            <span class="PolygonStyle_fillType_05" style="margin: auto">高流量路段(400~500)</span>
          </li>
          <li class="traceClassLi" >
            <div style="background-color: #b51500;width: 30px;height: 10px;margin: 10px 0px 10px 0px"></div>
            <span class="PolygonStyle_fillType_05" style="margin: auto">超高流量路段(>600)</span>
          </li>
        </ul>
      </div>
    <!--内嵌饼图-->
<!--      <div
          class="echart"
          id="mychart"
          style="width: 100%;height:160px;margin-top: 10px;padding-top: 20px"
      >
      </div>-->
    </template>

    <template #footer>
      <div style="flex: border-box">
        <el-button @click="hideRoadNet">显示/隐藏</el-button>
        <el-button @click="initBikeCountEcharts" v-show="isShowTraceClass">查看统计图</el-button>
        <el-button type="primary" @click="getxmRoadData">获取轨迹量</el-button>
      </div>
    </template>
  </el-dialog>

<!--内嵌弹出框-->
  <el-dialog  v-model="store.state.isShowGreenTrace"
              title="设置区间"
              width="25%"
              :modal="false"
              top="80px"
              style="position: absolute;left: 205px"
              draggable >
    <div class="slider-demo-block">
      <span class="demonstration">阈值大小</span>
      <el-slider v-model="bikeGreenTraceCounts" :step="100" show-stops max="1000"/>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="controlDialogVisible">显示/隐藏</el-button>
        <el-button @click="initGreenEcharts">查看统计图</el-button>
        <el-button type="primary" @click="sureToGetGreenTraces"
        >确认</el-button
        >
      </span>
    </template>
  </el-dialog>

<!--道路单车流量等级统计图 -->
  <el-dialog v-model="isShowBikeCountEcharts" width="35%" :modal="false" draggable>
    <div
        class="echart"
        id="mychart"
        style="width: 100%;height:160px;margin:auto;"
    >
    </div>
  </el-dialog>
  <!--按流量提取道路统计图-->
  <el-dialog v-model="isShowGreenEcharts" width="35%" :modal="false" draggable>
    <div
        class="echart"
        id="greenchart"
        style="width: 100%;height:160px;margin:auto;"
    >
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ElMessageBox,ClickOutside as vClickOutside } from 'element-plus'
import "../pages/Map.vue";
import { ref,unref , reactive, toRefs} from 'vue'
import store from "../store/index.js";
import axios from "axios";
import Point from "ol/geom/Point"
import WKT from "ol/format/WKT";
import { Fill, Stroke, Style, Text , Circle, Icon} from "ol/style";
import {Cluster,Vector as VectorSource} from 'ol/source';
import {Vector as VectorLayer} from 'ol/layer';
import Overlay from 'ol/Overlay'// 引入覆盖物模块
import 'ol/ol.css' // ol提供的css样式(必须引入)
import { showLoading, hideLoading } from '../store/loading.js'
//echarst表格
import * as echarts from "echarts";

//气泡弹出框
// 弹框
const overlay = ref(null) // 弹框实例
const mapContent = ref(null) // 弹框挂载的 dom 元素
const mapText = ref(null) // 弹框内容
//初始化弹框图层
// 创建弹框
const createOverlay = () => {
  overlay.value = new Overlay({
    element: mapContent.value, // 将弹框挂载在 dom 上
    autoPan: true, // 如果弹框显示不全则自动归位
    positioning: 'bottom-center', // 相对标点的实际位置
    stopEvent: false, // 冒泡
    autoPanAnimation: {
      duration: 300 // 地图移动速度
    }
  })
  store.state.map.addOverlay(overlay.value) // 将弹框添加到地图上
}
//关闭弹框
const closeMapPopup = () => {
  overlay.value.setPosition(undefined)
}


const isShowTraceCountsManage = ref(false)

const direction = ref('rtl')
const traceCountsDateRadio = ref('gj20201221')
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('Are you sure you want to close this?')
      .then(() => {
        done()
      })
      .catch(() => {
        // catch error
      })
}


//TopMenu通过Home.vue传值
export interface ExposeType {
  getIsShowTraceCountsMsg:Function
}
//将TopMenu中的isshowBikeTrace值传入
const  getIsShowTraceCountsMsg = (val:boolean) => {
  isShowTraceCountsManage.value = val
  console.log('val3',val)
}
//将值暴露
defineExpose({
  getIsShowTraceCountsMsg
})

//道路轨迹可视化
//初始化厦门road Vector&source
//全局变量
const getData=ref([])
const xmTraceCountsVector=ref(null)
const xmTraceCountsSource=ref(null)
const traceCountFeature=ref(null)
const traceCountsFeatureCube=ref([])
const isGetTraceCountsData=ref(false)
//traceClass 显示与隐藏
const isShowTraceClass=ref(false)
//控制路网图层显示与隐藏
const isShowTraceCounts=ref(true)
//各路段数量
const roadCounts=ref([])


//显示统计图变量
const isShowBikeCountEcharts=ref(false)
xmTraceCountsSource.value=new VectorSource({})
xmTraceCountsVector.value = new VectorLayer({
  name1:'轨迹量等级划分图层',
  source: xmTraceCountsSource.value,
  style: function (feature){
    var countClass = feature.get("TraceCount");
    var _color = "#2b93ce";
    if (countClass>0 && countClass<100) {
      _color = "#00b514";
      roadCounts.value[1]+=1;
    }
    else if (countClass>=100 && countClass<300) {
      _color = "#c1ff24";
      roadCounts.value[2]+=1
    }
    else if (countClass>=300 && countClass<500) {
      _color = "#eae830";
      roadCounts.value[3]+=1
    }
    else if (countClass>=500 && countClass<700) {
      _color = "#e0ad07";
      roadCounts.value[4]+=1
    }
    else if (countClass>=700 && countClass<900) {
      _color = "#bb8104";
      roadCounts.value[5]+=1
    }
    else if (countClass>=900) {
      _color = "#b51500";
      roadCounts.value[6]+=1
    }else {
      roadCounts.value[0]+=1
    }
    return new Style({
      stroke: new Stroke({
        color: _color,
        width: 5,
      }),
    })
  }
})


//显示/隐藏路网图层
const hideRoadNet=()=>{
  if(isShowTraceCounts.value){
    //隐藏
    xmTraceCountsVector.value.setVisible(false)
    isShowTraceCounts.value=!isShowTraceCounts.value
    isShowTraceClass.value=!isShowTraceClass.value
  }else{
    //显示
    xmTraceCountsVector.value.setVisible(true)
    isShowTraceCounts.value=!isShowTraceCounts.value
    isShowTraceClass.value=!isShowTraceClass.value
  }
}
//获取后台路网数据
const getxmRoadData=()=> {
  //展示Loading
  showLoading()
  axios.get(store.state.dbApi + '/xmRoadCount').then(result => {
    //清空变量/初始化变量
    getData.value = [];
    if(isGetTraceCountsData.value)
    {//已获取数据，清空变量
      xmTraceCountsSource.value.clear()
      traceCountsFeatureCube.value=[]
      //初始化roadcounts
      roadCounts.value[0]=0
      roadCounts.value[1]=0
      roadCounts.value[2]=0
      roadCounts.value[3]=0
      roadCounts.value[4]=0
      roadCounts.value[5]=0
      roadCounts.value[6]=0
    }else{//还未获取数据，加入图层，初始化图层
      //初始化roadcounts
      roadCounts.value[0]=0
      roadCounts.value[1]=0
      roadCounts.value[2]=0
      roadCounts.value[3]=0
      roadCounts.value[4]=0
      roadCounts.value[5]=0
      roadCounts.value[6]=0
      store.state.map.addLayer(xmTraceCountsVector.value)
      store.state.checkHighLayerList.push(xmTraceCountsVector.value.get('name1'))
      //激活地图点击事件
      traceCountMsgEvent()
      //// 初始化地图之后就将弹框挂载好，后续只是修改显示的位置
      createOverlay()
    }
    getData.value = result.data
    console.log(getData.value[0]['id'],getData.value[0]['road_id'],getData.value[0]['road_name'],getData.value[0]['traj_count'])
    //获取数据库数据并通过WKT转换放入图层
    for (let i = 0; i < getData.value.length; i++) {
      //加入点并设置属性
      traceCountFeature.value=new  WKT().readFeature(getData.value[i]['multiline'])
      //设置属性
      traceCountFeature.value.setProperties({
        name:'单车流量',
        id:getData.value[i]['id'],
        roadId:getData.value[i]['road_id'],
        roadName:getData.value[i]['road_name'],
        TraceCount:getData.value[i]['traj_count']
      })
      traceCountsFeatureCube.value.push(traceCountFeature.value)
    }
    isGetTraceCountsData.value=true

    //隐藏Loading
    hideLoading()
    //将线级加载到图源中
    xmTraceCountsSource.value.addFeatures(traceCountsFeatureCube.value)
    //traceClass显示
    isShowTraceClass.value=true
  })
}
//地图点击事件
const traceCountMsgEvent=()=>{
  let key=store.state.map.on("click", (e) =>{
    // console.log(e);
    let feature = store.state.map.forEachFeatureAtPixel(
        e.pixel,
        (feature, layer) => {
          return feature;
        }
    );

    if (feature &&feature.get('name')=='单车流量') {
      // 弹框内容
      mapText.value = "<ul>"+'<li>id：'+feature.get('id')+'</li>'+
      '<li>道路id：'+feature.get('roadId')+'</li>'+
      '<li>道路名称：'+feature.get('roadName')+'</li>'+
      '<li>单车流量：'+feature.get('TraceCount')+'辆'+'</li>'+
      '<li>流量状况：'+countClass(feature)+'</li>'+
      '<li>位置：'+e.coordinate[0].toFixed(9)+','+e.coordinate[0].toFixed(9)+'</li>'+
      "</ul>"
      // 把overlay 显示到指定的坐标位置
      overlay.value.setPosition(e.coordinate)
    } else {
      // 弹框关闭
      console.log('弹框关闭')
      closeMapPopup()
    }
   // store.state.map.un(key.type, key.listener)
  })

}
//流量弹框判断
const countClass = (feature) => {
  let countClass = feature.get("TraceCount");
  let result = "空闲路段";
  if (countClass>0 && countClass<100) result = "较小流量路段";
  else if (countClass>=100 && countClass<300) result = "小流量路段";
  else if (countClass>=300 && countClass<500) result = "中等流量路段";
  else if (countClass>=500 && countClass<700) result = "较高流量路段";
  else if (countClass>=700 && countClass<900) result = "高流量路段";
  else if (countClass>=900) result = "超高流量路段";
  return result
}

/*绿道图层*/
//初始化绿岛图层greenTraceVector、greenTraceSource
const greenTraceVector=ref(null)
const greenTraceSource=ref(null)
const greenTraceFeature=ref(null)
const greenTraceFeatureCube=ref([])
const isGetGreenTraceData=ref(false)
//traceClass 显示与隐藏
const isShowGreenTraceClass=ref(false)
//控制道路高流量路段的图层显示与隐藏
const isShowGreenTraceCounts=ref(true)
//控制多大流量的可以显示
const bikeGreenTraceCounts=ref(null)
//绿道饼图数据
const bikeGreenCountsData=ref([])
greenTraceSource.value=new VectorSource({})
greenTraceVector.value = new VectorLayer({
  name1:'高流量道路',
  source: greenTraceSource.value,
  style: function (feature){
    let countClass = feature.get("TraceCount");
    let _color = "#007712";
    if (countClass>0 && countClass<100) _color = "#04a41e";
    else if (countClass>=100 && countClass<200) _color = "#06cb27";
    else if (countClass>=200 && countClass<300) _color = "#2bea48";
    else if (countClass>=300 && countClass<400) _color = "#aaf191";
    else if (countClass>=400 && countClass<500) _color = "#efd2d2";
    else if (countClass>=500 && countClass<600) _color = "#f19999";
    else if (countClass>=600 && countClass<700) _color = "#f37070";
    else if (countClass>=700 && countClass<800) _color = "#da0606" ;
    else if (countClass>=800 && countClass<900) _color = "#9f0101";
    else if (countClass>=900 && countClass<1000) _color = "#730101";
    else if (countClass>=1000) _color = "#590202";
    return new Style({
      stroke: new Stroke({
        color: _color,
        width: 5,
      }),
    })
  }
})
//获取绿道数据
const getGreenTraceData=()=> {
  //展示Loading
  //获取单车流量大小
  let getBikeGreenTraceCount={
    trCount:bikeGreenTraceCounts.value
  }
  axios.post(store.state.dbApi + '/greenTrace',getBikeGreenTraceCount).then(result => {
    //清空变量/初始化变量
    getData.value = [];
    if(isGetGreenTraceData.value)
    {//已获取数据，清空变量
      greenTraceSource.value.clear()
      greenTraceFeatureCube.value=[]
    }else{//还未获取数据，加入图层，初始化图层
      store.state.map.addLayer(greenTraceVector.value)
      store.state.checkHighLayerList.push(greenTraceVector.value.get('name1'))
      //激活地图点击事件
      // traceCountMsgEvent()
      // //// 初始化地图之后就将弹框挂载好，后续只是修改显示的位置
      // createOverlay()
    }
    getData.value = result.data
    console.log(getData.value[0]['id'],getData.value[0]['road_id'],getData.value[0]['road_name'],getData.value[0]['traj_count'])
    //获取数据库数据并通过WKT转换放入图层
    for (let i = 0; i < getData.value.length; i++) {
      //加入点并设置属性
      greenTraceFeature.value=new  WKT().readFeature(getData.value[i]['multiline'])
      //设置属性
      greenTraceFeature.value.setProperties({
        name:'单车流量',
        id:getData.value[i]['id'],
        roadId:getData.value[i]['road_id'],
        roadName:getData.value[i]['road_name'],
        TraceCount:getData.value[i]['traj_count']
      })
      greenTraceFeatureCube.value.push(greenTraceFeature.value)
    }
    isGetGreenTraceData.value=true
    //traceClass显示
    isShowGreenTraceClass.value=true
    //隐藏Loading
    //将线级加载到图源中
    greenTraceSource.value.addFeatures(greenTraceFeatureCube.value)
  })
}

//获取绿道统计数据
const getGreenTraceCountData=()=>{
  //获取单车流量大小
  let getBikeGreenTraceCount={
    trCount:bikeGreenTraceCounts.value
  }
  //清空数据
  bikeGreenCountsData.value=[]
  greenColorCube.value=[]
  let getGreenCounts
  axios.post(store.state.dbApi + '/countGreen',getBikeGreenTraceCount).then(result => {
    getGreenCounts=result.data
    for(let i=0;i<getGreenCounts.length;i++){
      let obj = {
        name:'',
        value:''
      };
      obj.name = getGreenCounts[i]['name'];
      obj.value = getGreenCounts[i]['value'];
      bikeGreenCountsData.value.push(obj);
      //设置颜色
      greenTracePieColor(getGreenCounts[i]['valueClass'])
    }
  })
}
//绿道弹出框参数
//const selectValue = ref(0)
const controlDialogVisible = () => {
  if(isShowGreenTraceCounts.value){
    //隐藏
    greenTraceVector.value.setVisible(false)
    isShowGreenTraceCounts.value=!isShowGreenTraceCounts.value
  }else{
    //显示
    greenTraceVector.value.setVisible(true)
    isShowGreenTraceCounts.value=!isShowGreenTraceCounts.value
  }

}
//按下确认键
const sureToGetGreenTraces=()=>{
  //获取指定的绿道数据
  getGreenTraceData();
  //关闭
  store.commit('changeIsShowGreenTrace',true)
}

/*道路单车流量提取饼图*/
const isShowGreenEcharts=ref(false)
const initBikeCountEcharts=()=>{
  const option = {
    // legend: {
    //   // 图例
    //   data: ["空闲路段", "较小流量路段", "小流量路段", "中等流量路段", "较高流量路段","高流量路段","超高流量路段"],
    //   right: "10%",
    //   top: "30%",
    //   orient: "vertical"
    // },
    title: {
      // 设置饼图标题，位置设为顶部居中
      text: "道路单车流量情况",
      textStyle:{
        fontSize:17
      },
      top:'0%',
      left: "center",
    },
    series: [
      {
        top:'20%',
        bottom:'8%',
        type: "pie",
        label: {
          show: true,
          formatter: "{b} : {c} ({d}%)" // b代表名称，c代表对应值，d代表百分比
        },
        radius: ["30%", "70%"], //圆环内半径40%，外半径70%
        data: [
          {
            value: roadCounts.value[0],
            name: "空闲路段"
          },
          {
            value: roadCounts.value[1],
            name: "较小流量路段"
          },
          {
            value: roadCounts.value[2],
            name:  "小流量路段"
          },
          {
            value: roadCounts.value[3],
            name:  "中等流量路段"
          },
          {
            value: roadCounts.value[4],
            name: "较高流量路段"
          },
          {
            value: roadCounts.value[5],
            name: "高流量路段"
          },
          {
            value: roadCounts.value[6],
            name:  "超高流量路段"
          },

        ]
      }
    ]
  };
  //显示
  isShowBikeCountEcharts.value=true
  setTimeout(function (){
    let mchart=echarts.init(document.getElementById('mychart'))
    mchart.setOption(option)
  },800)
}

/*根据参数获取绿道饼图*/
const initGreenEcharts=()=>{
  //从后台获取数据
  getGreenTraceCountData()
  const option = {
    // legend: {
    //   // 图例
    //   data: ["空闲路段", "较小流量路段", "小流量路段", "中等流量路段", "较高流量路段","高流量路段","超高流量路段"],
    //   right: "10%",
    //   top: "30%",
    //   orient: "vertical"
    // },
    //设置饼图颜色
    color:greenColorCube.value,
    title: {
      // 设置饼图标题，位置设为顶部居中
      text: "单车流量大于"+bikeGreenTraceCounts.value+"辆的统计情况",
      textStyle:{
        fontSize:17
      },
      top:'0%',
      left: "center",
    },
    series: [
      {
        top:'20%',
        bottom:'8%',
        type: "pie",
        label: {
          show: true,
          formatter: "{b} : {c} ({d}%)" // b代表名称，c代表对应值，d代表百分比
        },
        radius: ["30%", "70%"], //圆环内半径40%，外半径70%
        data: bikeGreenCountsData.value
      }
    ]
  };
  //显示
  isShowGreenEcharts.value=true
  setTimeout(function (){
    let mchart=echarts.init(document.getElementById('greenchart'))
    mchart.setOption(option)
  },800)
}

/*根据数量大小设置颜色*/
const greenColorCube=ref([])
const greenTracePieColor=(count)=>{
  console.log(count)
  if(count>0 && count<100)
    greenColorCube.value.push("#04a41e")
  else if(count>=100 && count<200)
    greenColorCube.value.push("#06cb27")
  else if(count>=200 && count<300)
    greenColorCube.value.push("#2bea48")
  else if(count>=300 && count<400)
    greenColorCube.value.push("#aaf191")
  else if(count>=400 && count<500)
    greenColorCube.value.push("#efd2d2")
  else if(count>=500 && count<600)
    greenColorCube.value.push("#f19999")
  else if(count>=600 && count<700)
    greenColorCube.value.push("#f37070")
  else if(count>=700 && count<800)
    greenColorCube.value.push("#da0606")
  else if(count>=800 && count<900)
    greenColorCube.value.push("#9f0101")
  else if(count>=900 && count<1000)
    greenColorCube.value.push("#730101")
  else if(count>=1000)
    greenColorCube.value.push("#590202")
}

</script>

<style>
.traceClassLi{
  display: flex;
}
.ol-popup {
  position: absolute;
  background-color: white;
  box-shadow: 0 1px 4px rgba(0,0,0,0.2);
  padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 12px;
  left: -50px;
  min-width: 320px;
  /*隐藏*/
  z-index:-100
}
.ol-popup:after, .ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}
.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}
.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}
/*ul li设计*/
.ol-popup li{
  list-style-type :none;
  margin-left: auto;
  text-align: initial;
  font-size: initial;
  color: #504f4f;
}

/*绿道参数选择弹出框*/
.slider-demo-block {
  display: flex;
  align-items: center;
}
.slider-demo-block .el-slider {
  margin-top: 0;
  margin-left: 12px;
}
.slider-demo-block .demonstration {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  line-height: 44px;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 0;
}
.slider-demo-block .demonstration + .el-slider {
  flex: 0 0 70%;
}
</style>